import { NameSpace } from 'utils/index';
import exceed from 'utils/apimap';
import { Message } from '@teamix/ui';
import { ENUM } from 'utils/constants.js';
import intl from '../../../../../../../locale';

const ns = NameSpace('dashboardProjects');
export const RECEIVE_PROJECTS = ns('RECEIVE_PROJECTS');
export const CHANGE_PROJECTS = ns('CHANGE_PROJECTS');
export const CHANGE_SEARCH = ns('CHANGE_SEARCH');
export const UPDATE_DATA = ns('UPDATE_DATA');
export const SET_NAVKEY = ns('SET_NAVKEY');
export const RECEIVE_REPO_SETTING = ns('RECEIVE_REPO_SETTING');
// 获取企业当前套餐
export const ENTERPRISE_PACKAGE = ns('ENTERPRISE_PACKAGE');

const { organization } = window.FORCE;

export function setNavKey(data) {
  return (dispatch) => {
    dispatch({
      type: SET_NAVKEY,
      data: data || 'mine',
    });
  };
}

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

// counts接口专门用来查仓库数量，性能较好
export function getProjectsCounts() {
  return (dispatch, getState) => {
    const state = getState().organization.projects;
    const { search, archived } = state;

    exceed
      .forceFetch({
        api: 'projects.counts',
        data: {
          search,
          contains_sub_projects: true,
          archived,
        },
      })
      .then((result) => {
        dispatch({
          type: UPDATE_DATA,
          data: {
            totalMine: result.authorized,
            totalAll: result.all,
          },
        });
      });
  };
}

export function getProjects(page, clearType, per_page) {
  return (dispatch, getState) => {
    const state = getState().organization.projects;
    const { search, order_by, navKey, archived } = state;

    if (clearType === ENUM.clearType.all) {
      updateData({
        isLoading: true,
      })(dispatch);
    }

    exceed
      .forceFetch({
        api: navKey === 'mine' ? 'projects.authorizedList' : 'projects.exploreList',
        data: {
          page,
          search,
          order_by,
          group_by: navKey === 'mine' ? '' : 'star',
          per_page: per_page || 10,
          contains_sub_projects: navKey === 'mine' ? true : null,
          archived,
        },
      })
      .then((result) => {
        // 排序，清空所有
        if (clearType === ENUM.clearType.all) {
          dispatch({
            type: CHANGE_PROJECTS,
            data: Object.assign(result, {
              currentPage: page,
              list: result.list,
            }),
          });

          updateData({
            isLoading: false,
          })(dispatch);
          return;
        }
        // 正常
        dispatch({
          type: RECEIVE_PROJECTS,
          data: Object.assign(result, {
            currentPage: page,
          }),
        });
      });
  };
}

export function getSingleProjectInfo(projectId) {
  // projects.single.get
  return new Promise((resolve, reject) => {
    exceed
      .fetch({
        api: 'projects.single.get',
        params: {
          id: projectId,
        },
      })
      .then((result) => {
        resolve({
          result,
        });
      })
      .fail(() => {
        reject();
      });
  });
}

export function updateProject({ projectId, projects, projectsMap, dispatch, isStarred }) {
  // 相同ID的数据进行更新
  projects &&
    projects.forEach((project) => {
      if (project.id === projectId) {
        project.starred = isStarred;
        project.is_starred = isStarred;
      }
    });
  projectsMap &&
    Object.keys(projectsMap).forEach((curProjects) => {
      projectsMap[curProjects] &&
        projectsMap[curProjects].forEach((project) => {
          if (project.id === projectId) {
            project.starred = isStarred;
            project.is_starred = isStarred;
          }
        });
    });

  updateData({
    projects: [...projects],
    projectsMap: { ...projectsMap },
  })(dispatch);
}

export function changeSearch(value) {
  return {
    type: CHANGE_SEARCH,
    data: value,
  };
}

// 收藏
export function doStar(projectId) {
  return (dispatch, getState) => {
    const state = getState().organization.projects;
    const { projects, projectsMap } = state;

    exceed
      .forceFetch({
        api: 'projects.star',
        params: { projectId },
      })
      .then(() => {
        updateProject({ projectId, projects, projectsMap, dispatch, isStarred: true });
        Message.success({
          title: intl.get({
            id: 'code-assets.projects.actions.CollectedSuccessfully',
            defaultMessage: '收藏成功',
          }),
        });
      });
  };
}

// 取消收藏
export function doUnStar(projectId) {
  return (dispatch, getState) => {
    const state = getState().organization.projects;
    const { projects, projectsMap } = state;
    exceed
      .forceFetch({
        api: 'projects.unstar',
        params: { projectId },
      })
      .then(() => {
        updateProject({ projectId, projects, projectsMap, dispatch, isStarred: false });
        Message.success({
          title: intl.get({
            id: 'code-assets.projects.actions.Deleted',
            defaultMessage: '取消收藏成功',
          }),
        });
      });
  };
}

// 查询企业设置
export function getRepoSettingData() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'organization.repo.setting.get',
        params: {
          org_id: organization.id,
        },
      })
      .then((result) => {
        dispatch({
          type: RECEIVE_REPO_SETTING,
          data: result,
        });
      });
  };
}

// 获取企业当前套餐
export function getOrgplan(data) {
  return (dispatch) => {
    dispatch({
      type: ENTERPRISE_PACKAGE,
      data,
    });
  };
}
